from flask import Flask, jsonify, request
import os
import time
import socket
import random
from threading import Lock
import logging

app = Flask(__name__)

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 获取 Pod 信息
pod_name = os.environ.get('POD_NAME', socket.gethostname())
pod_ip = os.environ.get('POD_IP', '127.0.0.1')
node_name = os.environ.get('NODE_NAME', 'localhost')

# 请求计数器
request_count = 0
count_lock = Lock()

@app.route('/')
def hello():
    global request_count
    with count_lock:
        request_count += 1
    client_ip = request.headers.get('X-Forwarded-For', request.remote_addr)
    logger.info(f"Request #{request_count} from {client_ip} served by {pod_name}")
    
    return jsonify({
        'message': 'Hello from K8s Podman Demo!',
        'pod_name': pod_name,
        'pod_ip': pod_ip,
        'node_name': node_name,
        'request_count': request_count,
        'client_ip': client_ip,
        'timestamp': time.time()
    })

@app.route('/health')
def health():
    return jsonify({
        'status': 'healthy',
        'pod_name': pod_name,
        'timestamp': time.time()
    })

@app.route('/info')
def info():
    """返回详细的 Pod 信息"""
    global request_count
    with count_lock:
        request_count += 1
    
    return jsonify({
        'pod_name': pod_name,
        'pod_ip': pod_ip,
        'node_name': node_name,
        'hostname': socket.gethostname(),
        'request_count': request_count,
        'timestamp': time.time(),
        'environment': os.environ.get('ENVIRONMENT', 'development')
    })

@app.route('/cpu-intensive')
def cpu_intensive():
    """模拟 CPU 密集型任务"""
    global request_count
    with count_lock:
        request_count += 1
    
    start_time = time.time()
    
    # 模拟不同复杂度的计算
    complexity = random.randint(5000000, 15000000)
    result = 0
    for i in range(complexity):
        result += i * i
    
    end_time = time.time()
    processing_time = end_time - start_time
    
    logger.info(f"CPU intensive task completed in {processing_time:.2f}s by {pod_name}")
    
    return jsonify({
        'result': f"Calculated sum of squares up to {complexity}",
        'processing_time': f"{processing_time:.2f} seconds",
        'pod_name': pod_name,
        'request_count': request_count,
        'timestamp': time.time()
    })

@app.route('/memory-intensive')
def memory_intensive():
    """模拟内存密集型任务"""
    global request_count
    with count_lock:
        request_count += 1
    
    start_time = time.time()
    
    # 创建一个大列表来消耗内存
    size = random.randint(1000000, 3000000)
    large_list = [i * 2 for i in range(size)]
    
    # 执行一些操作
    result = sum(large_list)
    
    end_time = time.time()
    processing_time = end_time - start_time
    
    logger.info(f"Memory intensive task completed in {processing_time:.2f}s by {pod_name}")
    
    return jsonify({
        'result': f"Processed list of {size} elements",
        'processing_time': f"{processing_time:.2f} seconds",
        'pod_name': pod_name,
        'request_count': request_count,
        'timestamp': time.time()
    })

@app.route('/api/v1/users')
def get_users():
    """模拟 API 端点"""
    global request_count
    with count_lock:
        request_count += 1
    
    users = [
        {"id": 1, "name": "Alice", "pod": pod_name},
        {"id": 2, "name": "Bob", "pod": pod_name},
        {"id": 3, "name": "Charlie", "pod": pod_name}
    ]
    
    return jsonify({
        'users': users,
        'total': len(users),
        'served_by': pod_name,
        'timestamp': time.time()
    })

@app.route('/api/v1/products')
def get_products():
    """模拟另一个 API 端点"""
    global request_count
    with count_lock:
        request_count += 1
    
    products = [
        {"id": 1, "name": "Laptop", "price": 999.99, "pod": pod_name},
        {"id": 2, "name": "Mouse", "price": 29.99, "pod": pod_name},
        {"id": 3, "name": "Keyboard", "price": 79.99, "pod": pod_name}
    ]
    
    return jsonify({
        'products': products,
        'total': len(products),
        'served_by': pod_name,
        'timestamp': time.time()
    })

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=False)
